package com.knight;

import com.knight.handler.EventHandler;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventHandlerPool<E> implements BeanPostProcessor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * key -> beanName,value -> EventHandler
     */
    private Map<String, EventHandler> eventHandlerMap = new HashMap<>();

    /**
     * key -> eventType ,value -> List<EventHandler>
     */
    private Map<E, List<EventHandler>> eventHandlerListMap = new HashMap<>();

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        logger.debug("加载{}到eventHandlerMap中...", beanName);
        if (bean instanceof EventHandler) {
            eventHandlerMap.put(beanName, (EventHandler) bean);
            List<E> typeList = ((EventHandler<E, ?>) bean).supportEventTypeList();
            for (E eventType : typeList) {
                List<EventHandler> list = eventHandlerListMap.get(eventType);
                if (list == null) {
                    list = new ArrayList<>();
                    list.add((EventHandler) bean);
                    eventHandlerListMap.put(eventType, list);
                } else {
                    list.add((EventHandler) bean);
                }

            }
        }
        return bean;
    }

    public Map<E, List<EventHandler>> getEventHandlerListMap() {
        return eventHandlerListMap;
    }
}
